import {messages} from "share/common";
/**
 *  crated by jsq on 2017/9/27
 */
import React from 'react';
import { connect } from 'react-redux'
import ResizeTable from 'components/resize-table'
import budgetService from 'containers/budget-setting/budget-organization/budget-control-rules/budget-control-rulles.service'
import menuRoute from 'routes/menuRoute'
import { Form, Button, Icon, message, Popconfirm, } from 'antd';
import 'styles/budget-setting/budget-organization/budget-control-rules/budget-control-rules-detail.scss';
import SlideFrame from 'components/slide-frame'
import NewBudgetRulesDetail from 'containers/budget-setting/budget-organization/budget-control-rules/new-budget-rules-detail'
import UpdateBudgetRulesDetail from 'containers/budget-setting/budget-organization/budget-control-rules/update-budget-rules-detail'
import BasicInfo from 'components/basic-info'
import LanguageInput from 'components/template/language-input/language-input';

const FormItem = Form.Item;

class BudgetControlRulesDetail extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      loading: true,
      buttonLoading: false,
      data: [],
      edit: false,
      updateState: false,
      controlRule: {},
      strategyGroup:[],
      startValue: null,
      endValue: null,
      showSlideFrameCreate: false,
      showSlideFrameUpdate: false,
      ruleDetail: {},
      pagination: {
        current:0,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      infoList: [
        {type: 'input', id: 'controlRuleCode', required: true, disabled: true, label: messages('budget-setting.key19'/*控制规则代码*/)+" :" /*业务规则代码*/},
        {type: 'select', options: [], id: 'strategyGroupName', label: messages('budget-setting.key21'/*控制策略*/)+" :"},
        {type: 'items', id: 'effectiveDate',label: messages('budget-setting.key22'/*有效日期*/)+" :", items: [
          {type: 'date', id: 'startDate', label: messages('budget-setting.key22'/*有效日期*/)+" :", isRequired: true},
          {type: 'date', id: 'endDate', label: ' '}
        ]},
        {type: 'input', id: 'priority', required: true, disabled: true, label: messages('budget-setting.key23'/*优先级*/) /*优先级*/}
      ],
      extraInfo: [
        {type: 'input', id: 'controlRuleName', label: messages('budget-setting.key20'/*控制规则名称*/)+" :" /*业务规则名称*/},
      ],
      columns: [
        {          /*规则参数类型*/
          title: messages('budget-setting.key24'/*规则参数类型*/), key: "ruleParameterTypeDescription", dataIndex: 'ruleParameterTypeDescription',
          render: recode =>{
            return recode
          }
        },
        {          /*规则参数*/
          title: messages('budget-setting.key25'/*规则参数*/), key: "ruleParameterDescription", dataIndex: 'ruleParameterDescription'
        },
        {          /*取值方式*/
          title: messages('budget-setting.key26'/*取值方式*/), key: "filtrateMethodDescription", dataIndex: 'filtrateMethodDescription'
        },
        {          /*取值范围*/
          title: messages('budget-setting.key27'/*取值范围*/), key: "summaryOrDetailDescription", dataIndex: 'summaryOrDetailDescription'
        },
        {          /*下限值*/
          title: messages('budget-setting.key28'/*下限值*/), key: "parameterLowerLimit", dataIndex: 'parameterLowerLimit'
        },
        {          /*上限值*/
          title: messages('budget-setting.key29'/*上限值*/), key: "parameterUpperLimit", dataIndex: 'parameterUpperLimit'
        },
        {          /*失效日期*/
          title: messages('budget-setting.key30'/*失效日期*/), key: "invalidDate", dataIndex: 'invalidDate',
          render: description => (<span>{description === null ? "-" : description.substring(0,10)}</span>)
        },
        {title: messages('common.operation'), key: 'operation', width: '8%', render: (text, record) => (
          <span>
            <Popconfirm onConfirm={(e) => this.deleteItem(e, record)} title={messages('budget-setting.key218',{controlRule: record.controlRuleName}/*你确认要删除？*/)}>{/* 你确定要删除organizationName吗 */}
              <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
            </Popconfirm>
          </span>)},  //操作
      ],
      i18n: {}
    }
  }

  deleteItem = (e, record) => {
    budgetService.deleteRuleDetail(record.id).then(response => {
      message.success(messages('common.delete.success', {name: record.organizationName || ''})); // name删除成功
      this.getList();
    })
  };

  componentWillMount(){
    this.getList();
    //根据路径上的预算规则id查出完整数据
    budgetService.getRuleById(this.props.params.ruleId).then((response)=>{
      if(response.status === 200){
        let endDate = response.data.endDate === null ? "" : response.data.endDate.substring(0,10);
        response.data.effectiveDate = response.data.startDate.substring(0,10) + " ~ " +endDate;

        this.setState({
          controlRule: response.data,
          createParams: response.data,
          controlRuleName: response.data.controlRuleName,
          i18n: response.data.i18n || {}
        });

      }
    });
    //加载页面时，获取启用的控制策略
    budgetService.getStrategy({organizationId:this.props.params.id,isEnabled:true}).then((response)=>{
      if(response.status === 200){
        let strategyGroup = [];
        response.data.map((item)=>{
          let strategy = {
            id: item.id,
            key: item.id,
            label: item.controlStrategyCode+" - "+item.controlStrategyName,
            value: item.controlStrategyName,
            title: item.controlStrategyName
          };
          strategyGroup.addIfNotExist(strategy)
        });
        let infoList = this.state.infoList;
        infoList[1].options = strategyGroup;
        this.setState({infoList,strategyGroup})
      }
    })
  }

  handleChange = (e)=>{
    this.setState({
      buttonLoading: false,
    })
  };

  //新建规则明细,左侧划出
  showSlideCreate = (flag) => {
    this.setState({
      showSlideFrameCreate: flag,
      showSlideFrameUpdate: false
    })
  };

  //编辑规则明细,左侧划出
  showSlideUpdate = (flag) => {
    this.setState({
      showSlideFrameUpdate: flag,
      showSlideFrameCreate: false
    })
  };

  handleEdit = (record) =>{
    this.setState({
      ruleDetail: record,
      showSlideFrameUpdate: true,
      showSlideFrameCreate: false
    })
  };

  handleCloseSlideCreate = (params) => {
    if(params) {
      this.setState({
        loading: true,
        showSlideFrameCreate: false
      });
      this.getList();
    }
  };

  handleCloseSlideUpdate = (changed)=>{
    if(changed)
      this.setState({
        showSlideFrameUpdate: false,
        loading: true
      },this.getList())
  };

  //保存编辑后的预算规则
  handleUpdate = (values)=>{
    let { controlRuleName, i18n, controlRule } = this.state;
    const {versionNumber,strategyGroupId,isEnabled,isDeleted,createdBy} = controlRule;
    let startTime = new Date(values.startDate);
    startTime.setHours(startTime.getHours()+8);
    values.startDate = startTime;
    if(values.endDate !== null){
      let endTime = new Date(values.endDate);
      endTime.setHours(endTime.getHours()+8);
      values.endDate = endTime;
    }
    values.organizationId = this.props.params.id;
    values.id = this.props.params.ruleId;
    values = { ...values, ...{ versionNumber, strategyGroupId, isEnabled, isDeleted, createdBy, i18n, controlRuleName } };
    this.state.strategyGroup.map((item)=>{
      if(item.value === values.strategyGroupName){
        values.strategyGroupId = item.id;
      }
    });
    budgetService.updateRule(values)
      .then((response) => {
        if (response) {
          let endDate = response.data.endDate === null ? '' : response.data.endDate.substring(0, 10);
          response.data.effectiveDate = response.data.startDate.substring(0, 10) + ' ~ ' + endDate;
          response.data.strategyGroupName = {
            label: values.strategyGroupName,
            value: values.strategyGroupName,
            key: values.strategyGroupId
          };
          controlRule = response.data;
          message.success(messages('budget-setting.key31'/*保存成功！*/)); /*保存成功！*/
        }
      })
      .catch((e) => {
        if (e.response) {
          message.error(`${messages('common.operate.filed')}, ${e.response.data.message}`);
        }
      })
      .finally(()=>{
        this.setState({ controlRule, updateState: true, loading: false }, this.handleUpdateState);
      });
  };

  handleUpdateState = () => {
    this.setState({ updateState: false });
  };

  //获取规则明细
  getList(){
    const {pagination} = this.state;
    this.setState({ loading: true });
    budgetService.getRuleDetail({controlRuleId: this.props.params.ruleId,page:pagination.page,size:pagination.pageSize}).then((response)=>{
      if(response.status === 200){
        response.data.map((item)=>{
          item.key = item.id
        });
        let pagination = this.state.pagination;
        pagination.total = Number(response.headers['x-total-count']);
        this.setState({
          loading: false,
          data: response.data,
          pagination
        })
      }
    })
  }


  //返回预算规则页面
  handleBack = () => {
    this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key').children.budgetOrganizationDetail.url.replace(':id', this.props.params.id)+ '?tab=RULE');
  };

  //分页点击
  onChangePager = (pagination,filters, sorter) =>{
    let temp = this.state.pagination;
    temp.page = pagination.current-1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      loading: true,
      pagination: temp
    }, ()=>{
      this.getList();
    })
  };

  handleI18n = (name, value) => {
    let { i18n, controlRuleName } = this.state;
    i18n.controlRuleName = value;
    controlRuleName = name;
    this.setState({ controlRuleName, i18n });
  };

  renderExtraFields = () => {
    const { i18n, extraInfo } = this.state;
    const { form: { getFieldDecorator } } = this.props;
    return extraInfo.map(item =>
      <FormItem label={item.label}>
        {getFieldDecorator(item.id, {
          initialValue: this.state[item.id],
          rules: [{
            required: item.isRequired,
            message: messages('common.can.not.be.empty', { name: item.label }),  //name 不可为空
          }]
        })(
          <LanguageInput
            key={item.id}
            isEdit={true}
            i18nName={i18n[item.id] || null}
            nameChange={this.handleI18n}
            placeholder={messages('common.please.enter')/* 请输入 */}
            mainLanguageIsRequired={!!item.isRequired}/>
        )}
      </FormItem>
    )
  };

  render(){
    const { loading, data, infoList, pagination, columns, showSlideFrameCreate,showSlideFrameUpdate, ruleDetail,
      controlRule, updateState, extraInfo } = this.state;
    return(
      <div className="budget-control-rules-detail">
        <BasicInfo
          infoList={infoList}
          infoData={controlRule}
          extraFields={this.renderExtraFields()}
          extraFieldsIndex={1}
          extraInfo={extraInfo}
          handelEvent={this.handleChange}
          updateHandle={this.handleUpdate}
          updateState={updateState}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${pagination.total}`})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button onClick={()=>this.showSlideCreate(true)} type="primary" >{messages('common.create')}</Button>  {/*新建*/}
          </div>
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={columns}
          onRow={record => ({
            onClick: () => this.handleEdit(record)
          })}
          pagination={pagination}
          onChange={this.onChangePager}
          size="middle"
          bordered/>
        <a style={{fontSize:'14px',paddingBottom:'20px'}} onClick={this.handleBack}><Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')}</a>

        <SlideFrame title= {messages('budget-setting.key32'/*新建规则明细*/)}
                    show={showSlideFrameCreate}
                    content={NewBudgetRulesDetail}
                    afterClose={this.handleCloseSlideCreate}
                    onClose={() => this.showSlideCreate(false)}
                    params={{ruleId:this.props.params.ruleId}}/>

        <SlideFrame title= { messages('budget-setting.key33'/*编辑规则明细*/)}
                    show={showSlideFrameUpdate}
                    content={UpdateBudgetRulesDetail}
                    afterClose={this.handleCloseSlideUpdate}
                    onClose={()=>this.showSlideUpdate(false)}
                    params={ruleDetail}/>
      </div>
    )
  }
}

BudgetControlRulesDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}

const WrappedBudgetControlRulesDetail = Form.create()(BudgetControlRulesDetail);

export default connect(mapStateToProps)(WrappedBudgetControlRulesDetail);
